package com.example.run_game;

import java.text.DecimalFormat;
import java.util.ArrayList;

import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.model.LatLng;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ToggleButton;

public class RunInfoFragment extends Fragment
	{
		public static ArrayList<Location> route;
		public String routename;
		private View view;
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public RunInfoFragment(){}
		public static final String ARG_SECTION_NUMBER = "section_number";

		public static RunInfoFragment newInstance(ArrayList<Location> mMarkers, int xp, String routeName, int calories)
		{
	        System.out.println("newinstance");
			RunInfoFragment f = new RunInfoFragment();
	        System.out.println("setting bundle");

	        Bundle args = new Bundle();
	        args.putParcelableArrayList("route", mMarkers);
	        args.putInt("xp", xp);
	        args.putString("routename", routeName);
	        args.putInt("calories", calories);
	        f.setArguments(args);
	        
	        System.out.println("Args added.");
	        System.out.println(f);
	        
	        
	        return f;
	        
		}

	    protected void setupProgressBar(int totalExperienceGained, boolean isHistorical)
		{	       
			DbManager db = new DbManager(getActivity().getApplicationContext());
			Player player = new Player(db);
			if (!isHistorical)
				player.awardXP(totalExperienceGained);
			int percentage = player.getProgressBarPercentage();
			int lvl = player.getLevel();	 
			Log.d("UI:", "Setting up xp bar");
			Log.d("UI:", "experience gained:"+totalExperienceGained);
			Log.d("UI:", "xp:"+player.getXp());
			Log.d("UI:", "percentage:"+player.getProgressBarPercentage());
			Log.d("UI:", "level: "+ player.getLevel());
			
			((ProgressBar)view.findViewById(R.id.progressBar)).setProgress(percentage);
			((TextView)view.findViewById (R.id.level_lower_text)).setText(""+lvl);	
			((TextView)view.findViewById (R.id.level_upper_text)).setText(""+(lvl+1));
		}
		
		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState)
		{
			view = inflater.inflate(R.layout.fragment_run_statistics, container, false);
			return view;
		}
		
		@Override
		public void onResume()
		{
			super.onResume();
			
			final Button button = (Button) getView().findViewById(R.id.quitRunButton);
			if (button == null) return;
			if (getArguments()==null)
				return;
			
			System.out.println(getArguments());
			ArrayList<Parcelable> l = getArguments().getParcelableArrayList("route");
			final Integer experience = getArguments().getInt("xp");
			ArrayList<Location> route = new ArrayList<Location>(l.size());
			final Integer calories 	= getArguments().getInt("calories");

			if (calories == 0) // historical data
				setupProgressBar(experience, true);
			else
				setupProgressBar(experience, false);

			for (Parcelable parcelable : l)
			{
				Location loc = (Location)parcelable;
				System.out.println(loc);
				route.add(loc);
			}
			System.out.println(route);
			if (experience == 0)
			{
				button.setVisibility(Button.INVISIBLE);
			}
			else
			{
		        button.setOnClickListener(new OnClickListener()
				{
					
					@Override
					public void onClick(View arg0)
					{
						Intent intent = new Intent(getActivity().getBaseContext(), MainMenu.class);
						ArrayList<Parcelable> l = getArguments().getParcelableArrayList("route");
						ArrayList<Location> route = new ArrayList<Location>(l.size());
	
						for (Parcelable parcelable : l)
						{
							Location loc = (Location)parcelable;
							System.out.println(loc);
							route.add(loc);
						}
						Log.d("save","route="+route);
						Log.d("save","routename="+getArguments().getString("routename"));
						
						Log.d("GAME: ", "Testing achievements one last time");
						
						DbManager db = new DbManager(getActivity().getApplicationContext());
						AchievementManager am = new AchievementManager(db);
						am.testAchievementsEndGame();							
								
						Utils.addNewRouteToIndex(route, getArguments().getString("routename"),getView().getContext());
						updateDatabase(route, experience, calories, getActivity());
					    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
					}
				});
			}
		
			long millis = route.get(route.size()-1).getTime() -
					route.get(0).getTime();
			String result = Utils.formatMilliTime(millis,false);
			TextView tmp = (TextView) getView().findViewById(R.id.timeValue);
			tmp.setText(result);

			double distance = Utils.RouteDistance(route)/1000;
			DecimalFormat df = new DecimalFormat("#.###");
			
			TextView d = (TextView)getView().findViewById(R.id.distValue);
			d.setText((df.format(distance))+" km");

			int totalSeconds = (int) (millis/1000);
			System.out.println("seconds="+totalSeconds);
			System.out.println("distance="+distance+"km");
			System.out.println("speed="+(distance*1.0)/totalSeconds+"kps");
			System.out.println("speed="+(distance*1.0)/((1.0*totalSeconds)/3600)+"kph");
			double speed = distance*1.0 / (1.0*totalSeconds/3600);
			df = new DecimalFormat("#.##");
			
			TextView sp = (TextView)getView().findViewById(R.id.speedValue);
			sp.setText(df.format(speed)+" kph");
			
			TextView eg = (TextView)getView().findViewById(R.id.expValue);
			if (experience == 0)
				eg.setText(((int)(distance*2107.0))+"");
			else
				eg.setText(experience+"");

			TextView cv = (TextView)getView().findViewById(R.id.calorieValue);
			if (calories == 0)
				cv.setText(Utils.calcCalories(distance*1000, 75)+"");
			else
				cv.setText(calories+"");
			populateProfileBar(getView());
		}

		private void populateProfileBar(View view)
		{
			DbManager db = new DbManager(view.getContext());
			Player mPlayer = new Player(db);
			ImageView profilePic = (ImageView)view.findViewById(R.id.list_image);
			Bitmap picture = mPlayer.getPicture();
			if(picture != null)
				profilePic.setImageBitmap(picture);
			DecimalFormat df = new DecimalFormat("#.##");

			TextView playerName = (TextView)view.findViewById(R.id.title);
			playerName.setText(mPlayer.getName().toString());
			TextView distTime = (TextView)view.findViewById(R.id.distance);
			distTime.setText("Total Dist/Time: "+df.format(mPlayer.getTotalDistance()/1000)+"km/"+ Utils.formatMilliTime(mPlayer.getTotalTime(),false));
			TextView avSpeed = (TextView)view.findViewById(R.id.average_speed);
			avSpeed.setText("Average Speed: "+df.format(mPlayer.getAvSpeed()*60*60/1000)+" kph");
			TextView calories = (TextView)view.findViewById(R.id.calories);
			calories.setText("Calories Burned: "+Integer.toString(mPlayer.getTotalCaloriesBurned()));
		}

		public void updateDatabase(ArrayList<Location> route, int experience,
				int cals, Context context)
		{
			DbManager db = new DbManager(context);
			Player player = new Player(db);
			double dist = Utils.RouteDistance(route);
			long time = route.get(route.size()-1).getTime()-route.get(0).getTime();
			player.endGame(dist, time, 0, cals, (1.0*dist/(time/1000)), experience);
		}
		

		
	}
